const express = require("express");
const { User, Course, Like } = require("../../models");
const { success, failure } = require("../../utils/responses");
const router = express.Router();
const { NotFoundError, BadRequestError } = require("../../utils/errors");
const bcrypt = require("bcryptjs");
const { paging } = require("../../utils/utils");

/**
 * 点赞,取消赞
 * POST /likes
 */
router.post("/", async function (req, res, next) {
  try {
    // 当前登录人
    const userId = req.userId;
    const { courseId } = req.body; //课程ID
    const course = await Course.findByPk(courseId);
    if (!course) {
      throw new BadRequestError("课程不存在");
    }
    // 检查是否已经点赞
    const like = await Like.findOne({
      where: {
        courseId,
        userId,
      },
    });
    if (!like) {
      await Like.create({ courseId, userId });
      await course.increment("likesCount", { by: 1 }); // +1
      success(res, "点赞成功.");
    } else {
      await like.destroy();
      await course.decrement("likesCount", { by: 1 }); // -1
      success(res, "取消点赞.");
    }
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询用户点过赞的课程
 * GET /likes
 */
router.get("/", async function (req, res, next) {
  try {
    // 获取分页参数
    const { query, currentPage, pageSize, offset } = paging(req);
    // 排序+分页
    // 查询当前用户
    const user = await User.findByPk(req.userId);
    const condition = {
      //不查询关联表
      joinTableAttributes: [],
      attributes: { exclude: ["CategoryId", "UserId", "content"] },
      order: [["id", "DESC"]],
      limit: pageSize,
      offset: offset,
    };
    const courses = await user.getLikeCourses(condition);
    const count = await user.countLikeCourses();
    success(res, "查询用户点赞的课程成功.", {
      courses,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
